<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/2
 * Time: 15:35
 */
declare(strict_types=1);

namespace App\Service;

use App\Model\Dao\CommissionSaleDao;
use App\Model\Dao\MchConfigDao;
use App\Model\Dao\MchInfoDao;
use App\Model\Dao\RateCommissionSalesDao;
use App\Model\Dao\StatMonthlyTradeDao;
use App\Model\Dao\SysAdminDao;
use App\Model\Dao\TradeOrderDetailDao;
use App\Utils\CustomUtils;
use Hyperf\Di\Annotation\Inject;

class CommissionMchService
{

    /**
     * @Inject()
     * @var SysAdminDao
     */
    private $SysAdminDao;

    /**
     * @Inject()
     * @var MchInfoDao
     */
    private $MchInfoDao;

    /**
     * @Inject()
     * @var RateCommissionSalesDao
     */
    private $RateCommissionSalesDao;

    /**
     * @Inject()
     * @var StatMonthlyTradeDao
     */
    private $StatMonthlyTradeDao;

    /**
     * @Inject()
     * @var MchConfigDao
     */
    private $MchConfigDao;

    /**
     * @Inject()
     * @var CommissionSaleDao
     */
    private $CommissionSaleDao;

    /**
     * @param $startTime 开始时间
     * @param $endTime 结束时间
     * @param array $salesIds 销售员id，可以单独统计某个销售员。只取二级来算，不能取一级来算
     * @param bool $isForce 是否强制，是的话会把已经生成的软删除再生成
     */
    public function stat($startTime, $endTime, $statMonth, $salesIds = [], $isForce = false) {
        // 先取这些二级销售员
        $saleLevel2List = null;

        if (empty($salesIds)) {
            $saleLevel2List = $this->SysAdminDao->getAllSales([2]);
        } else {
            $saleLevel2List = $this->SysAdminDao->getSalesByIds($salesIds, [2]);
        }
        // 查二级关联的佣金比例
        $rateCommission2 = $this->RateCommissionSalesDao->getWhere(['level' => 2]);
        if (empty($rateCommission2)) {
            CustomUtils::xzxDebug('未设置二级佣金比例');
            return;
        }
        foreach ($saleLevel2List as $sales) {
            $this->statSalesLevel2($sales, $rateCommission2, $statMonth, $startTime, $endTime, $isForce);
        }

        if (empty($saleLevel2List)) {
            return;
        }

        // 查一级关联的佣金比例
        $rateCommission1 = $this->RateCommissionSalesDao->getWhere(['level' => 1]);
        if (empty($rateCommission1)) {
            CustomUtils::xzxDebug('未设置一级佣金比例');
            return;
        }
        // 查找这些二级销售的上级
        $saleLevel1List = $this->SysAdminDao->getParentByChildrenIds($salesIds);
        foreach ($saleLevel1List as $sales) {
            $this->statSalesLevel1($sales, $rateCommission1, $statMonth, $startTime, $endTime, $isForce);
        }
    }

    /**
     * @param $sales
     * @param $rateCommission
     * @param $statMonth
     * @param $startTime
     * @param $endTime
     * @param $isForce
     * 单个一级销售统计
     */
    private function statSalesLevel1($sales, $rateCommission, $statMonth, $startTime, $endTime, $isForce) {
        $isCommission = $this->CommissionSaleDao->getWhere([
            'salesId'   => $sales['id'],
            'statMonth' => $statMonth,
            'delFlag'   => 0,
        ]);

        if ($isForce && !!$isCommission) {
            // 强制成功且有数据就删除
            $this->CommissionSaleDao->delWhere([
                'salesId'   => $sales['id'],
                'statMonth' => $statMonth,
                'delFlag'   => 0,
            ]);
        } else if (!$isForce && !!$isCommission) {
            // 有数据就不管了
            return;
        }

        // 汇总
        $statList = $this->StatMonthlyTradeDao->getWhereList(['salesLevel1' => $sales['id'], 'statMonth' => $statMonth, 'delFlag' => 0]);
        foreach ($statList as $stat) {
            $mchConfig = $this->MchConfigDao->getWhere(['mchId' => $stat['mchId']]);

            // 写入
            $data = [
                'id'            => CustomUtils::createUUID(),
                'statMonth'     => $statMonth,
                'mchId'         => $stat['mchId'],
                'mchNo'         => $stat['mchNo'],
                'successCount'  => $stat['successCount'],
                'settleAmount'  => $stat['successSettleAmount'],
                'serviceFee'    => $stat['serviceFee'],
                'commission'    => $stat['salesCommission1'],
                'salesId'       => $sales['id'],
                'settleCurrency'=> $mchConfig['settleCurrency'],
                'level'         => 1,
                'commissionRate'=> $rateCommission['rate'],
                'statStartTime' => $startTime,
                'statEndTime'   => $endTime,
                'createTime'    => time()
            ];
            $this->CommissionSaleDao->add($data);
        }
    }

    /**
     * @param $sales
     * @param $rateCommission
     * @param $statMonth
     * @param $startTime
     * @param $endTime
     * @param $isForce
     * 单个二级销售员统计
     */
    private function statSalesLevel2($sales, $rateCommission, $statMonth, $startTime, $endTime, $isForce) {
        bcscale(8);

        $isCommission = $this->CommissionSaleDao->getWhere([
            'salesId'   => $sales['id'],
            'statMonth' => $statMonth,
            'delFlag'   => 0,
        ]);

        if ($isForce && !!$isCommission) {
            // 强制成功且有数据就删除
            $this->CommissionSaleDao->delWhere([
                'salesId'   => $sales['id'],
                'statMonth' => $statMonth,
                'delFlag'   => 0,
            ]);
        } else if (!$isForce && !!$isCommission) {
            // 有数据就不管了
            return;
        }


        // 查看关联的商户
        $mchList = $this->MchInfoDao->getWhereList(['salesId' => $sales['id']]);

        // 查看商户关联渠道统计
        foreach ($mchList as $mch) {

            // 查已经统计好的商户数据
            $statTrade = $this->StatMonthlyTradeDao->getWhere([
                'mchId'     => $mch['id'],
                'statMonth' => $statMonth,
                'delFlag'   => 0,
            ]);
            if (empty($statTrade)) {
                CustomUtils::xzxDebug("{$mch['mchNo']} 未完成统计");
                continue;
            }

            $mchConfig = $this->MchConfigDao->getWhere(['mchId' => $statTrade['mchId']]);

            // 自己的
            $data = [
                'id'            => CustomUtils::createUUID(),
                'statMonth'     => $statMonth,
                'mchId'         => $mch['id'],
                'mchNo'         => $mch['mchNo'],
                'successCount'  => $statTrade['successCount'],
                'settleAmount'  => $statTrade['successSettleAmount'],
                'serviceFee'    => $statTrade['serviceFee'],
                'commission'    => $statTrade['salesCommission2'],
                'salesId'       => $sales['id'],
                'settleCurrency'=> $mchConfig['settleCurrency'],
                'level'         => 2,
                'commissionRate'=> $rateCommission['rate'],
                'statStartTime' => $startTime,
                'statEndTime'   => $endTime,
                'createTime'    => time()
            ];
            $this->CommissionSaleDao->add($data);
        }

    }
}